package controller

import (
	"fmt"
	"math/rand"
	"smc-admin/models"
	"smc-admin/response"
	"smc-admin/utils"

	"golang.org/x/crypto/bcrypt"

	"github.com/gin-gonic/gin"
)

type Client struct {
	Phone    string `form:"phone" binding:"required"`    //用户名
	Password string `form:"password" binding:"required"` //密码
}

// @Tags         登陆注册
// @Summary      登陆
// @Description  用户登陆
// @Param        login  body	Client  true  "用户登陆表单"
// @Success      200	{object}	response.Body
// @Router       /client/login [post]
func Login(ctx *gin.Context) {
	var client map[string]string
	err := ctx.ShouldBindJSON(&client)
	if err != nil {
		panic(err.Error())
	}

	//验证用户
	m := models.User{
		Phone: client["phone"],
	}
	user, res := m.Find()
	if res != nil {
		panic(res.Error)
	}
	if len(user) == 0 {
		panic("账号不存在")
	}

	//验证密码
	passwordRes := bcrypt.CompareHashAndPassword([]byte(user[0].Password), []byte(client["password"]))
	if passwordRes != nil {
		panic("密码错误")
	}

	token, err := utils.CreateJwt(utils.TokenInfo{
		ID:         user[0].ID,
		UpdateTime: user[0].UpdateTime.Unix(),
	})
	if err != nil {
		panic(err.Error())
	}

	response.Success(ctx, response.Body{
		Data: token,
	})
}

// @Tags         登陆注册
// @Summary      注册
// @Description  用户注册
// @Param        register  body      Client  true  "用户注册表单"
// @Success      200       {object}  response.Body
// @Router       /client/register [post]
func Register(ctx *gin.Context) {
	var client Client
	//绑定注册用户表单
	err := ctx.ShouldBindJSON(&client)
	if err != nil {
		panic(err.Error())
	}
	//验证并添加注册用户
	m := models.User{
		Phone: client.Phone,
	}
	//验证手机号是否存在
	user, res := m.Find()
	if len(user) != 0 {
		panic("账号存在")
	}
	if res != nil {
		panic(res.Error())
	}
	//处理密码
	hash, _ := bcrypt.GenerateFromPassword([]byte(client.Password), bcrypt.DefaultCost)
	m.Password = string(hash)

	m.UserName = fmt.Sprintf("smc_%v%v", client.Phone[len(client.Phone)-4:], rand.Intn(9999-1000)+1000)
	//添加用户
	addErr := m.Add()
	if addErr != nil {
		panic(addErr.Error())
	}
	response.Success(ctx)
}
